/*
 * InputHandler.cpp
 *
 *  Created on: 05.10.2013
 *      Author: dima
 */


#include "InputHandler.hpp"


#include <iostream>
namespace
{
  void dbg_ShowCharBinary(char c)
  {
    if(c & 0x80) std::cout << "1"; else std::cout<< "0";
    if(c & 0x40) std::cout << "1"; else std::cout<< "0";
    if(c & 0x20) std::cout << "1"; else std::cout<< "0";
    if(c & 0x10) std::cout << "1"; else std::cout<< "0";
    if(c & 0x08) std::cout << "1"; else std::cout<< "0";
    if(c & 0x04) std::cout << "1"; else std::cout<< "0";
    if(c & 0x02) std::cout << "1"; else std::cout<< "0";
    if(c & 0x01) std::cout << "1"; else std::cout<< "0";
    std::cout << std::endl;
  }
}



Tanks::
Controller::
InputHandler::
InputHandler(Tanks::Model::PlayerModel * argPlayer):
  m_player(argPlayer),
  m_pressedButtons(0)
{}


bool
Tanks::
Controller::
InputHandler::
handleInput()
{
  SDL_Event event;
  while(SDL_PollEvent(&event))
  {
    switch(event.type)
    {
    case SDL_QUIT:
      return false;
    case SDL_KEYDOWN:
      if(event.key.keysym.sym == SDLK_LEFT)
      {
        m_pressedButtons = m_pressedButtons | 0x8;
        m_player->SetVelocity(-1, 0);
      }
      if(event.key.keysym.sym == SDLK_UP)
      {
        m_pressedButtons = m_pressedButtons | 0x4;
        m_player->SetVelocity(0, -1);
      }
      if(event.key.keysym.sym == SDLK_RIGHT)
      {
        m_pressedButtons = m_pressedButtons | 0x2;
        m_player->SetVelocity(1, 0);
      }
      if(event.key.keysym.sym == SDLK_DOWN)
      {
        m_pressedButtons = m_pressedButtons | 0x1;
        m_player->SetVelocity(0, 1);
      }
      if(event.key.keysym.sym == SDLK_SPACE)
      {
        m_player->Shoot();
      }
      break;
    case SDL_KEYUP:
      if(event.key.keysym.sym == SDLK_LEFT)
      {
        m_pressedButtons = m_pressedButtons & 0x7;
      }
      if(event.key.keysym.sym == SDLK_UP)
      {
        m_pressedButtons = m_pressedButtons & 0xB;
      }
      if(event.key.keysym.sym == SDLK_RIGHT)
      {
        m_pressedButtons = m_pressedButtons & 0xD;
      }
      if(event.key.keysym.sym == SDLK_DOWN)
      {
        m_pressedButtons = m_pressedButtons & 0xE;
      }

      if(m_pressedButtons == 0x0)
      {
        m_player->SetVelocity(0, 0);
      }
      else if((m_pressedButtons & 0x8) != 0x0)
      {
        m_player->SetVelocity(-1, 0);
      }
      else if((m_pressedButtons & 0x4) != 0x0)
      {
        m_player->SetVelocity(0, -1);
      }
      else if((m_pressedButtons & 0x2) != 0x0)
      {
        m_player->SetVelocity(1, 0);
      }
      else if((m_pressedButtons & 0x1) != 0x0)
      {
        m_player->SetVelocity(0, 1);
      }
      break;
    }
  }
  return true;
}


